var cs = new CSInterface();

String.prototype.bind = function(eventFunctionStr) {
	var params = pickParams(eventFunctionStr)

  	var val = {}
	_$.each(params, function(idx, param){
    	val[param] = {}

		_$.each(getSubElemIds(param), function(i, id){
     	 	val[param][id] = {}
			var _this = _$('#' + id)
			
			var tagName = _$(_this)[0].tagName
			if (_this.attr('contenteditable')) {
				bindContenteditableEvent(_this, val, param, id)
			} else if (tagName === 'SELECT') {
				val[param][id].val = _this.val()
				_this.on('change', function(){
					val[param][id].val = _this.val()
				})
			} else if (tagName === 'INPUT') {
				val[param][id].val = _this.val()
				_this.on('change', function(){
					val[param][id].val = _this.val()
				})
			} else if (tagName === 'BUTTON') {
				_this.on('click', function(){
					_this.addClass('active')
					cs.evalScript('getFilePath("' + id + '")');
				})
			} else {
				val = bindCheckEvent(_this, val, param, id)
			}
		})
	})


    _$('#' + this).click(function(){
		val = updateVal(val, params)
        var paramString = '(' + JSON.stringify(val) + ')'
		evalScript(val, eventFunctionStr, paramString)
    })
}

// =========================handleActions=========================== //
/*
 * htmlId.bind( 'eventFunction(htmlId1, htmlId2)' )
 */

'checkFormat'.bind('checkFormat(fmtOption)')

// ================================================================= //

function  evalScript(val, eventFunctionStr, paramString){
	var funcString = eventFunctionStr.replace(/\([^\)]*\)/g, paramString);
	try { 
		console.log(eventFunctionStr)  
		console.log(val)
	} catch (error) { /* _$.write(error) */ }

	try {
		cs.evalScript(funcString);
	} catch (error) {
		// alert(error)
	}		
}

function updateVal(val, params) {
	_$.each(params, function(idx, param){
		_$.each(getSubElemIds(param), function(i, id){
			var _this = _$('#' + id)
			
			var tagName = _$(_this)[0].tagName
			var contenteditable = _this.attr('contenteditable')

			if (contenteditable) {
				val[param][id].val = _$(_this).html()
				val[param][id].on = JSON.parse(contenteditable) &&  !!_$(_this).html()
			} else if (tagName === 'SELECT') {
			} else if (tagName === 'INPUT') {
			} else {
				// console.log(id, _this.hasClass('active'))
				if (_$(_this).attr('val')) {
					val[param][id].val = _this.attr('val')
				} else {
					delete val[param][id].val
				}
				val[param][id].on = _this.hasClass('active')
			}
		})
	})
	return val
}

function bindCheckEvent(_this, val, param, id) {
	val[param][id].val = _this.attr('val')
	val[param][id].on = _this.hasClass('active')

	_this.on('click', function() {
		// console.log(id, ': ', _this.attr('name'))
		if (_this.attr('name')) {
			turnOffOthers(_this)	
		} else {
			_this.toggleClass('active')
		}
		val[param][id].val = _this.attr('val')
		val[param][id].on = _this.hasClass('active')
		toggleTarget(_this.attr('toggle'), _this.hasClass('active'))
		
	})	
	function toggleTarget(target, status) {
		if (!target) { return }
		targetIds = target.split(' ')
		_$.each(targetIds, function(i, id){
			_$('#' + id).attr('contenteditable', status)
		})
	}
	function turnOffOthers(_this) {
		var name = _this.attr('name')
		var type = _this.attr('type')
		_$('div[name$="' + name + '"]').each(function(idx, dom) {
			if(_this.html() !== _$(this).html() ) {
				_$(this).removeClass('active')
			} else {
				if(type !== 'radio') {
					_$(this).toggleClass('active')
				} else {
					_$(this).addClass('active')
				}
			}
		})
	}
	return val
}

function bindContenteditableEvent(_this, val, param, id) {
	togglePlaceholder(_this)
	val[param][id].val = _$(_this).html()
	val[param][id].on = !!_$(_this).html()

	_this.on('input', function(){
		val[param][id].val = _$(this).html()
		val[param][id].on = !!_$(this).html()
		togglePlaceholder(_this)
	})

	function togglePlaceholder(_this) {
		var htm = _this.html()
		if (htm.length!= 0 && htm!='<br>') {
			_this.removeClass('place-show')
		} else {
			_this.addClass('place-show')
		}	
	}
}

function pickParams(eventFunctionStr) {
	var start = eventFunctionStr.indexOf('(') + 1
	var end = eventFunctionStr.indexOf(')')
    var eventParams = eventFunctionStr.substring(start, end)
	functionParams = eventParams.split(',').map(function(item) {
		return item.trim()
	})
	return(functionParams)
}

function getSubElemIds(id) {
	var elemIds = []
	_$('#' + id).find('div').each(function(index, elem) {
		var id = _$(elem).attr('id')
		if (id) {
			elemIds.push(id)
		}
	})
	_$('#' + id).find('select').each(function(index, elem) {
		var id = _$(elem).attr('id')
		if (id) {
			elemIds.push(id)
		}
	})
	_$('#' + id).find('input').each(function(index, elem) {
		var id = _$(elem).attr('id')
		if (id) {
			elemIds.push(id)
		}
	})
	_$('#' + id).find('button').each(function(index, elem) {
		var id = _$(elem).attr('id')
		if (id) {
			elemIds.push(id)
		}
	})
	return elemIds
}
